<?php

namespace App\Models;

use Image;

class BucketLog extends BaseModel
{
    protected $table = "bucket_log";

    protected $rules = [
        'order_id' => 'required',
        'shop_id' => 'required',
        'worker_id' => 'required',
        'worker_code' => 'required',
        'bucket_category_id' => 'required',
        'buyer_id' => 'required',
        'buyer_name' => 'required',
        'bucket_num' => 'required|numeric|min:1',
    ];

    protected $message = [
        'order_id.required' => '订单信息获取失败',
        'shop_id.required' => '店铺信息获取失败',
        'worker_id.required' => '送水工信息获取失败',
        'worker_code.required' => '送水工信息获取失败',
        'bucket_category_id.required' => '水桶分类信息获取失败',
        'buyer_id.required' => '买家信息获取失败',
        'buyer_name.required' => '买家信息获取失败',
        'bucket_num.required' => '水桶数量必须填写',
        'bucket_num.numeric' => '水桶数量必须是纯数字',
        'bucket_num.min' => '水桶数量不能小于1',
    ];

    public function category()
    {
        return $this->hasOne('App\Models\BucketCategory', 'id', 'bucket_category_id');
    }

    public function worker()
    {
        return $this->hasOne('App\Models\worker', 'id', 'worker_id');
    }


    public function getLogWithCategoyByOrderId($orderId)
    {
        return $res = $this->multiSelect('recive_order_money,recive_bill_money,bucket_num')
            ->multiWhere(['order_id' => $orderId])->get();
    }


    public function getOwnLogList()
    {
        $keyword = request('keyword');
        $where['shop_id'] = request('shop_id');
        $where['bucket_category_id'] = request('bucket_category_id');
        if ($keyword) {
            if (is_numeric($keyword)) {
                $where['worker_id'] = $keyword;
            } else {
                $where['buyer_name'] = ['like', '%' . $keyword . '%'];
            }
        }
        $rows = $this->_getJoinPageList('worker', $where, '*', ['id' => 'desc']);
        return $rows;
    }

    public function getLogListByShopId($shopId)
    {
        $keyword = request('keyword');
        $where['shop_id'] = $shopId;
        if ($keyword) {
            if (is_numeric($keyword)) {
                $where['worker_code'] = $keyword;
            } else {
                $where['buyer_name'] = ['like', '%' . $keyword . '%'];
            }
        }
        $rows = $this->_getPageList($where, 'id,goods_name,goods_num,goods_price');
        return $rows;
    }

    public function addOrUpdate()
    {
//`order_id` int(11) NOT NULL DEFAULT '0' COMMENT '订单ID',
//`shop_id` int(11) NOT NULL DEFAULT '0' COMMENT '店铺id',
//`worker_id` int(11) NOT NULL DEFAULT '0' COMMENT '送水工ID',
//`worker_code` int(11) NOT NULL DEFAULT '0' COMMENT '送水工工号',
//`bucket_category_id` int(11) NOT NULL DEFAULT '0' COMMENT '水桶分类ID',
//`buyer_id` int(11) NOT NULL DEFAULT '0' COMMENT '买家ID',
//`buyer_name` char(20) NOT NULL DEFAULT '' COMMENT '买家姓名',
//`num` int(11) NOT NULL DEFAULT '0' COMMENT '回桶数量',
        $data['order_id'] = intval(trim(request('order_id')));
        $data['shop_id'] = intval(trim(request('shop_id')));
        $data['worker_id'] = intval(trim(request('worker_id')));
        $data['worker_code'] = intval(trim(request('worker_code')));
        $data['buyer_id'] = trim(request('buyer_id'));
        $data['buyer_name'] = trim(request('buyer_name'));
        $data['bucket_num'] = intval(trim(request('bucket_num')));
        $data['bucket_category_id'] = request('bucket_category_id');
        if (request('id')) {
            $data['id'] = trim(request('id'));
        } else {
            $data['addtime'] = time();
        }
        if (!$this->_validate($data)) {
            return false;
        }
        //开启事务
        $res = $this->_save($data);
        if (!$res) {
            $this->error = '保存商品信息失败！';
            $this->_rollBack(); //回滚
            return false;
        }
        if (!isset($data['id'])) {
            //新增商品同时更新shop表商品总数
            $shop = new Shop();
            $shop->_inc(['id' => $data['shop_id']], 'total_goods_num');
        }
        $id = isset($data['id']) ? $data['id'] : $this->id;
        $picture = new Picture();
        $res = $picture->upload($id);
        if (!$res) {
            $this->error = $picture->getError();
            $this->_rollBack(); //回滚
            return false;
        }
        //记录行为
        action_log('update_goods', 'goods', $id);
        //提交事务
        $this->_commit();
        return $res;
    }

    public function del()
    {
        $id = request('id');
        if (!$id) {
            $this->error = '请选择要操作的数据!';
            return false;
        }
        $child = $this->_getList(['pid' => $id])->toArray();
        if (!empty($child)) {
            $this->error = '请先删除该品牌下的子品牌';
            return false;
        }
        $res = $this->_del(['id' => $id]);
        if (!$res) {
            $this->error = '删除品牌失败!';
            return false;
        }
        //记录行为
        action_log('update_shop', 'shop', $id);
        return '删除品牌成功';
    }


    public function addLog(array $bucket_nums, array $bucket_category_ids, array $order_info, $back = 1)
    {
//  (1) 送水工填写完成表单，该表单中包含水桶分类选择bucket_category_id，和水桶数量bucket_num
//
//  (2) 更新order表，status=20, back_bucket_num=(送水工表单数据),dispatch=2
//
//	(3) 更新member表，total_bucket_num=(递增，该值为order表中bucket_num字段值), total_back_bucket_num=(递增，该值为送水工表单数据)
//      更新member表用户借用桶borrow_bucket数据，该数据算法公式
//						（期初水桶+送水累计-回桶累计-自备桶-押金桶）【自备桶 押金桶 都是手动录入  借用桶是系统计算】
//
//	(4) 更新shop表，total_bucket_num=(递增，该值为order表中bucket_num字段值), total_back_bucket_num=(递增，该值为送水工表单数据),
//		[线下订单流程：sale_money = (递增，该值为order表中order_amount字段值)]
//
//	(5) 更新worker表，total_order_num=(递增1), total_bucket_num=(递增，该值为order表中bucket_num字段值),
//      total_back_bucket_num=(递增，该值为送水工表单数据)
//
//	(6) 更新bucket_data表，对应bucket_category_id下的total_bucket_num=(递增，该值为orderGoods表中goods_num字段值),
//		total_back_bucket_num=(递增，该值为送水工表单数据),
//
//	(7) 线下订单流程：更新shop_goods表，对应id下的sale_num=(递增，该值为orderGoods表中goods_num字段值),
//
//	(8) 添加bucket_log表日志信息

//        if (!empty($bucket_nums) && empty($bucket_category_ids)) {
//            $this->error = '请输入水桶数量!';
//            return false;
//        }
//        if (empty($bucket_nums) && !empty($bucket_category_ids)) {
//            $this->error = '请选择水桶品牌';
//            return false;
//        }
//        if (empty($order_info)) {
//            $this->error = '订单信息错误!';
//            return false;
//        }
        $this->_start();
        try {
            // 计算提成 by YuFan
            $commissionModel = new MemberCommission();
            $desc = $order_info['bill_id'] > 0 ? '水票购买' : '零售购买';
            $numArray = $commissionModel->orderNumHandle($order_info['id'], $order_info['buyer_id']);
            $commissionModel->commissionHandle($order_info['buyer_id'], $order_info['shop_id'], $numArray, $desc);

            // 库存减少
            $shopGoods = new ShopGoods();
            foreach($order_info['order_goods'] as $v) {
                $shopGoods->_dec(['id'=>$v['shop_goods_id']],'goods_num',$v['goods_num']);
            }

            $num = 0;
            if ($back) {
                $num = array_sum($bucket_nums);
            }
            $order = new Order();
            $orderData = [
                'status' => 20,
                'back_bucket_num' => $num,
                'dispatch' => 2,
            ];
            // 记录支付时间
            if($order_info['payment_time'] == 0) {
                $orderData['payment_time'] = time();

            }
            $a = $order->_update(['id' => $order_info['id']],$orderData);//(2)
//            tolog('a---' . $a);
            $commonData = [
                'total_bucket_num' => "`total_bucket_num` + {$order_info['bucket_num']}",
                'total_back_bucket_num' => "`total_back_bucket_num` + $num",
            ];
            $send_number = 0;
            $recive_order_money = floatval(request('recive_order_money',0));
            $recive_bill_money = floatval(request('recive_bill_money',0));
            $time = time();
            $formatTime = date('Y-m-d H:i:s', $time);
            $backData = [];
            if ($back) {
                $backLogData = new BackLogData();
                $bucketData = new BucketData();
                $buckeLogIn = new BucketLogIn();
                $member = new Member();
                $memberInfo = $member->_getOneById($order_info['buyer_id'], 'initial_bucket_num,total_bucket_num,total_back_bucket_num,cash_bucket_num');
                foreach ($order_info['order_goods'] as $k=>$v) {
                    if ($v['goods_category_id'] == $order->back_category_id) {
                        $send_number += $v['goods_num'];
                        $incData = [
                            'bucket_num_in' => "`bucket_num_in` - {$v['goods_num']}",
                            'bucket_num_out' => "`bucket_num_out` + {$v['goods_num']}",
                        ];
                        $where['shop_id'] = $order_info['shop_id'];
                        $where['bucket_category_id'] = $v['bucket_category_id'];
//                        tolog('where');
//                        tolog($where);
//                        tolog('incData');
//                        tolog($incData);
                        $a = $bucketData->_updateOrigin($where, $incData); //(6)
//                        tolog('L---' . $a);
                        //记录店内水桶日志 type:1.店内期初+ 2.进货入桶+ 3.进货回桶- 4.新购水桶+ 5.售出水桶- 6.送桶- 7.回桶+
                        $a = $buckeLogIn->addLog($order_info['admin_id'], $order_info['shop_id'], $v['bucket_category_id'], $v['goods_num'],$order_info['id'],$order_info['worker_id'], 6);
//                        tolog('buckeLogIn_6---' . $a);
                        $backData[] = [
                            'shop_id' => $order_info['shop_id'],
                            'worker_id' => $order_info['worker_id'],
                            'buyer_id' => $order_info['buyer_id'],
                            'order_id' => $order_info['id'],
                            'log_id' => 0,
                            'bucket_category_id' => $v['bucket_category_id'],
                            'num' =>  $v['goods_num'],
                            'type' => 2,
                            'created_at' => $formatTime,
                            'updated_at' => $formatTime,
                        ];
                    }
                }
//                tolog($backData);
//                $m = $backLogData->_add($backData);
//                    tolog('sm---' . $m);
                if ($send_number > 0) {
                    $total_bucket_num = $memberInfo['total_bucket_num'] + $send_number;
                    $total_back_bucket_num = $memberInfo['total_back_bucket_num'] + $num;
                    $memberData = [
                        'total_bucket_num' => $total_bucket_num,
                        'total_back_bucket_num' => $total_back_bucket_num,
                        'borrow_bucket_num' => $memberInfo['initial_bucket_num'] + $total_bucket_num - $total_back_bucket_num - $memberInfo['cash_bucket_num'],
                    ];
//                    tolog($memberData);
                    $a = $member->_update(['id' => $order_info['buyer_id']], $memberData);//(3)
//                    tolog('b---' . $a);
                }
            }
            //水票订单完成时商品销量和水票数据并记录水票消费日志
            if ($order_info['bill_id'] && !$order_info['type']) {
                //更新商品销量
                $shopGoods = new ShopGoods();
                foreach ($order_info['order_goods'] as $v) {
                    $a = $shopGoods->_updateOrigin(['id' => $v['shop_goods_id']], ['sale_num' => "`sale_num` + {$v['goods_num']}"]); //(7)
//                    tolog(['id' => $v['shop_goods_id'], 'sale_num' => "`sale_num` + {$v['goods_num']}"]);
//                    tolog('c---' . $a);
                }
//                $billLog = new MemberWaterBillLog();
//                $a = $billLog->log($order_info, $order_info['order_goods'][0], 3);
//                tolog('d---' . $a);
            }
            $shop = new Shop();
            $shopData = [];
//            if ($back) {
//                $shopData = [
//                    'total_bucket_num' => "`total_bucket_num` - $send_number + $num",
//                    'total_back_bucket_num' => "`total_back_bucket_num` + $num",
//                ];
//            }
            //线下订单完成时更新店铺销售额
            if ($order_info['type']) {
                if (!$order_info['bill_id']) {
                    $shopData['sale_money'] = "`sale_money` + {$order_info['order_amount']}";
                    if ($recive_order_money != $order_info['order_amount']) {
                        $this->error = '订单款金额与实际金额不一致，请重新打开订单详情，查看最新数据';
                        $this->_rollBack();
                        return false;
                    }
                }
                //更新商品销量
                $shopGoods = new ShopGoods();
//                tolog('order_goods');
//                tolog($order_info['order_goods']);
                foreach ($order_info['order_goods'] as $v) {
//                    tolog('update-shop-goods');
//                    tolog(['id' => $v['shop_goods_id'], 'sale_num' => "`sale_num` + {$v['goods_num']}"]);
                    $a = $shopGoods->_updateOrigin(['id' => $v['shop_goods_id']], ['sale_num' => "`sale_num` + {$v['goods_num']}"]); //(7)
//                    tolog('e---' . $a);
                }
            } else {
                $recive_order_money = 0;
            }
            //判断是否有未收水票款，有的话则更新销售额递增值为水票款，并更新水票销量
            $waterBillOrder = new WaterBillOrder();
//            tolog('mid----' . $order_info['buyer_id']);
            $bonus = [];
            $result = $waterBillOrder->_getList(['mid' => $order_info['buyer_id'], 'pay_status' => 10, 'type' => 1], 'waterbill_id,order_amount,total_num,description')->toArray();
//            tolog('result---' . count($result));
            if (!empty($result)) {
                //更新水票为已收款
                $a = $waterBillOrder->_update(['mid' => $order_info['buyer_id'], 'pay_status' => 10, 'type' => 1], ['pay_status' => 20, 'order_id' => $order_info['id'], 'payment_time' => time()]);
//                tolog('更新水票为已收款');
//                tolog(['mid' => $order_info['buyer_id'], 'pay_status' => 10, 'type' => 1, 'pay_status' => 20, 'order_id' => $order_info['id'], 'payment_time' => time()]);
//                tolog('f---' . $a);
                //更新水票销量
                $waterBill = new WaterBill();
                foreach ($result as $v) {
                    if ($v['description']) {
                        $bonus[] = $v['description'];
                    }
                    $a = $waterBill->_inc(['id' => $v['waterbill_id']], 'sale_num');
//                    tolog('g---' . $a);
                }
                //线下水票收款完成时更新店铺销售额
                $money = 0;
                $total_water_bill_num = 0;
                foreach ($result as $v) {
                    $money += $v['order_amount'];
                    $total_water_bill_num += $v['total_num'];
                }
                if ($recive_bill_money != $money) {
                    $this->error = '水票款金额与实际金额不一致，请重新打开订单详情，查看最新数据';
                    $this->_rollBack();
                    return false;
                }
                $recive_bill_money = $money;
                if (isset($shopData['sale_money'])) {
                    $money += $order_info['order_amount'];
                }
                $shopData['sale_money'] = "`sale_money` + $money";
                $shopData['total_water_bill_num'] = "`total_water_bill_num` + $total_water_bill_num";
            } else {
                $recive_bill_money = 0;
            }
//            tolog('shopData');
//            tolog($shopData);
            if (!empty($shopData)) {
                $a = $shop->_updateOrigin(['id' => $order_info['shop_id']], $shopData);//(4)
//                tolog('h---' . $a);
            }
            if ($recive_order_money || $recive_bill_money) {
                $bonusData = [
                    'order_id' => $order_info['id'],
                    'shop_id' => $order_info['shop_id'],
                    'worker_id' => $order_info['worker_id'],
                    'buyer_id' => $order_info['buyer_id'],
                    'buyer_name' => $order_info['buyer_name'],
                    'recive_order_money' => floatval($recive_order_money),
                    'recive_bill_money' => floatval($recive_bill_money),
                    'bonus' => !empty($bonus) ? json_encode($bonus) : '',
                    'addtime' => $time,
                    'created_at' => $formatTime,
                    'updated_at' => $formatTime,
                ];
                $bonus = new BonusLog();
//                tolog('bonusData');
//                tolog($bonusData);
                $a = $bonus->_add($bonusData);
//                tolog('n---' . $a);
            }
            if ($back) {
                $logData = [
                    'order_id' => $order_info['id'],
                    'shop_id' => $order_info['shop_id'],
                    'worker_id' => $order_info['worker_id'],
                    'buyer_id' => $order_info['buyer_id'],
                    'buyer_name' => $order_info['buyer_name'],
                    'send_num' => $send_number,
                    'bucket_num' => $num,
                    'description' => '送水回桶',
                    'addtime' => $time,
                    'created_at' => $formatTime,
                    'updated_at' => $formatTime,
                ];
//                tolog($logData);
                $logId = $this->_insert($logData); //(8)
//                tolog('j---' . $logId);
                if ($num && !empty($bucket_nums) && !empty($bucket_category_ids) && count($bucket_nums) == count($bucket_category_ids)) {
                    foreach ($bucket_nums as $k => $v) {
                        $bData = [
                            'bucket_num_in' => "`bucket_num_in` + $v",
                            'bucket_num_out' => "`bucket_num_out` - $v",
                        ];
                        $where['shop_id'] = $order_info['shop_id'];
                        $where['bucket_category_id'] = $bucket_category_ids[$k];
//                        tolog($where);
//                        tolog($bData);
                        $a = $bucketData->_updateOrigin($where, $bData); //(6)
//                        tolog('i---' . $a);
                        $backData[] = [
                            'shop_id' => $order_info['shop_id'],
                            'worker_id' => $order_info['worker_id'],
                            'buyer_id' => $order_info['buyer_id'],
                            'order_id' => $order_info['id'],
                            'log_id' => $logId,
                            'bucket_category_id' => $bucket_category_ids[$k],
                            'num' =>  $v,
                            'type' => 1,
                            'created_at' => $formatTime,
                            'updated_at' => $formatTime,
                        ];
                        //记录店内水桶日志 type:1.店内期初+ 2.进货入桶+ 3.进货回桶- 4.新购水桶+ 5.售出水桶- 6.送桶- 7.回桶+
                        $a = $buckeLogIn->addLog($order_info['admin_id'], $order_info['shop_id'], $bucket_category_ids[$k], $v, $order_info['id'], $order_info['worker_id'],7);
//                        tolog('buckeLogIn_7---' . $a);
                    }
                }
                if (!empty($backData)) {
                    foreach ($backData as &$v) {
                        $v['log_id'] = $logId;
                    }
                    $m = $backLogData->_add($backData);
                }
            }
            $worker = new Worker();
            $commonData['total_order_num'] = '`total_order_num`+ 1';
//            tolog($commonData);
            $a = $worker->_updateOrigin(['id' => $order_info['worker_id']], $commonData);//(5)
//            tolog('k---' . $a);

            $this->_commit();
            return true;
        } catch (\Exception $e) {
            $this->_rollBack();
            $this->error = '提交数据不完整，请重新提交!';
            return false;
        }
    }
}
